package com.flyone.herbal.utils;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Random;

/**
 * 邮件工具
 */
@Component
public class MailUtils {
    @Resource
    private JavaMailSender javaMailSender;
    // 发送邮件的账号
    private String FROM = "2122473540@qq.com";
    // 发件人昵称
    private String SUBJECT = "别卷了玩会吧-团队";

    /**
     * 生成指定长度的随机验证码
     *
     * @param length 验证码长度
     * @return 随机验证码
     */
    public String generateCode(int length) {
        // 定义验证码字符集
        String characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        // 创建随机数生成器
        Random random = new Random();
        StringBuilder codeBuilder = new StringBuilder();
        // 生成指定长度的随机验证码
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            char code = characters.charAt(index);
            codeBuilder.append(code);
        }
        return codeBuilder.toString();
    }

    /**
     * 发送邮件
     *
     * @param code 验证码
     */
    public void sendMail(String code, String to) {
        // 创建简单邮箱发送工具
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        // 设置发送方
        mailMessage.setFrom(FROM);
        // 设置接受方
        mailMessage.setTo(to);
        // 设置主题
        mailMessage.setSubject(SUBJECT);
        // 设置内容
        mailMessage.setText(code);
        // 发送邮件
        javaMailSender.send(mailMessage);
    }
}